import * as THREE from 'three'
import { MyGLTFLoader } from './loaders/MyGLTFLoader.js'
import { MyRGBELoader } from './loaders/MyRGBELoader.js'
// import { AssetContainer } from './AssetContainer.js'
class AssetManager {
    constructor(onLoad, onProgress, onError) {
        // Inherit LoadingManager components with callback events
        this.loadingManager = new THREE.LoadingManager(
            onLoad,
            onLoaderProgress.bind(onProgress),
            onError
        )
        // Initialize cache and loaders
        // this.assetModelLoader = new AssetModelLoader(this)
        // this.assetTextureLoader = new AssetTextureLoader(this)
        // this.assetAudioLoader = new AssetAudioLoader(this)
        // this.assetJSONLoader = new AssetJSONLoader(this)
        this.firstScreenAssets = {
            models: {
                url: '/assets/models.json',
                handler: this.loadModels.bind(this),
            },
            textures: {
                url: '/assets/textures.json',
                handler: this.loadTextures.bind(this),
            },
        }

        this.load(this.firstScreenAssets)
    }

    load(assets) {
        Object.entries(assets).forEach(([key, { url, handler }]) => {
            fetch(url)
                .then((response) => response.json())
                .then((data) => {
                    handler(data)
                })
        })
    }
    loadModels(models) {
        if (MyGLTFLoader.instance === null) {
            MyGLTFLoader.instance = new MyGLTFLoader(this.loadingManager)
        }
        MyGLTFLoader.instance.setPath('/gltf/')
        models.forEach((model) => {
            MyGLTFLoader.instance.load(model)
        })
    }
    loadTextures(textures) {
        console.error('ok', textures)
        if (MyRGBELoader.instance === null) {
            MyRGBELoader.instance = new MyRGBELoader(this.loadingManager)
        }
        MyRGBELoader.instance.setPath('/equirectangular/')
        textures.forEach((texture) => {
            MyRGBELoader.instance.load(texture)
        })
    }
}

// Set default progress event behavior
function onLoaderProgress(url, itemsLoaded, itemsTotal) {
    // Calculate percent
    var percent = Math.ceil((itemsLoaded / itemsTotal) * 100)

    // Dispatch loading progress to window listeners
    dispatchEvent(
        new CustomEvent('updateLoading', {
            detail: {
                url: url,
                itemsLoaded: itemsLoaded,
                itemsTotal: itemsTotal,
                percent: percent,
            },
        })
    )

    // Execute optional callback assigned from constructor
    if (typeof this == 'function') this(url, itemsLoaded, itemsTotal)
}

export { AssetManager }
